// components/lottery-modal/index.js
let reqJs = require('../../utils/req.js')


Component({
    options: {
        addGlobalClass: true,
    },
    properties: {
        zuItem: {
            type: Object,
            value: {}
        },
        show: {
            type: Boolean,
            value: false
        },
        prizeList: {
            type: Array,
            value: []
        }
    },

    data: {
        isRolling: false,
        currentIndex: 0,
        itemWidth: 100 // 根据奖品数量动态计算
    },

    observers: {
        'prizeList'(val) {
            this.setData({
                itemWidth: 100 / (val.length || 1)
            })
        }
    },

    methods: {
        // 关闭弹窗
        closeModeAi(e) {
            console.log(e)

            // if(e.currentTarget.dataset.text){

            // }
            // this.triggerEvent('closeModeAi', {
            //     data: e.currentTarget.dataset.text ? e.currentTarget.dataset.text :'关闭生成中的窗口'
            // })
            this.setData({
                show: false
            })
        },
        handleStart() {
            if (this.data.isRolling) return

            this.triggerEvent('start')
            this.startLottery()
        },

        async startLottery() {
            try {


                // 调用抽奖接口（实际替换为你的接口调用）
                // const { result } = await this.getLotteryResult()

                let result
                reqJs.luckDraw(this.data.zuItem.id).then(res => {

                    this.setData({
                        isRolling: true
                    })


                    // res.data.gid





                    if (res.data.gid == 16) {

                        let popupData = {
                            giftName: "很遗憾 未中奖",
                            giftImage: "https://data-h5.oss-cn-shenzhen.aliyuncs.com/yang/2025/0403/hongqi/0408/0419/kq.png",
                            rid: 0,
                        }

                        this.setData({
                            isRolling: false
                        })
                        setTimeout(() => {
                            this.triggerEvent('finish', popupData)
                        }, 100)
                        return
                    }


                    console.log('>>>>>', res)

                    result = res.data


                    const targetIndex = this.findPrizeIndex(result.gid)

                    if (targetIndex === -1) {
                        throw new Error('Invalid prize id')
                    }

                    this.runAnimation(targetIndex, result)

                })


            } catch (error) {
                console.error('抽奖失败:', error)
                this.setData({
                    isRolling: false
                })
            }
        },

        findPrizeIndex(gid) {
            console.log(this.data.prizeList)
            return this.data.prizeList.findIndex(item => item.gid == gid)
        },

        runAnimation(targetIndex, result) {
            const {
                prizeList
            } = this.data
            const total = prizeList.length
            let current = 0
            let speed = 100
            let rounds = 3 // 基础循环次数
            let steps = 0

            const animate = () => {
                current = (current + 1) % total
                this.setData({
                    currentIndex: current
                })
                steps++

                // 加速阶段
                if (steps < total * rounds) {
                    speed = Math.max(50, speed - 2)
                }
                // 减速阶段
                else {
                    speed = Math.min(300, speed + 20)

                    // 到达目标位置停止
                    if (current === targetIndex && speed >= 300) {

                        this.setData({
                            isRolling: false
                        })

                        setTimeout(() => {
                            this.triggerEvent('finish', result)
                        }, 100)



                        return
                    }
                }

                setTimeout(animate, speed)
            }

            animate()
        },

        // 模拟接口调用（替换为实际接口）
        getLotteryResult() {

            // reqJs.prizeDrawAction().then(res => {
            //   console.log('>>>>>', res)

            //   resolve({ result: res.data })


            // })
            // return new Promise(resolve => {
            //   setTimeout(() => {
            //     // 随机返回一个奖品ID
            //     const randomIndex = Math.floor(Math.random() * this.data.prizeList.length)
            //     resolve({ result: this.data.prizeList[randomIndex] })
            //   }, 100)
            // })
        }
    }
})